<script lang="ts" setup>
import type { DataFormOptionsProps } from '#/components/data-form/types';

import { nextTick, ref } from 'vue';

import { getDeptTree } from '#/api';
import { DataForm } from '#/components/data-form';

import { useForm } from './data';

const dataFormRef = ref<InstanceType<typeof DataForm>>();
const treeSelectRef = ref();
const deptTreeData = ref<any[]>([]);
const { fields, rules } = useForm();

// 展示弹窗
const open = (options: DataFormOptionsProps) => {
    getDeptTree()
        .then(({ data }) => {
            deptTreeData.value = data;
        })
        .then(() => {
            dataFormRef.value?.open(options);
            nextTick(() => {
                treeSelectRef.value?.remove(options.data?.id);
            });
        });
};

defineExpose({ open });
</script>

<template>
    <DataForm ref="dataFormRef" :fields="fields" :rules="rules" title="部门" api="/system/dept">
        <template #parentId="{ form }">
            <el-tree-select
                ref="treeSelectRef"
                v-model="form.parentId"
                :data="deptTreeData"
                :default-expanded-keys="[form.parentId]"
                :props="{ label: 'name' }"
                node-key="id"
                filterable
                check-strictly
                clearable
            />
        </template>
    </DataForm>
</template>